package com.redmoon.oa.pvg;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.StrUtil;

import com.redmoon.oa.kernel.License;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class OnlineUserMgr {
    public OnlineUserMgr() {
        super();
    }

    public static long getStayTime(HttpServletRequest req) {
        long st = 0;
        Authorization auth = Privilege.getAuthorization(req);
        if (auth!=null) {
            st = auth.getStayTime();
        }
        return st;
    }

    public static void refreshStayTime(HttpServletRequest req) throws
            ErrMsgException {
        setStayTime(req);
    }

    public static void setStayTime(HttpServletRequest req) throws
                ErrMsgException {
            Authorization auth = Privilege.getAuthorization(req);
            if (auth==null) {
                return;
            }
            auth.setStayTime(System.currentTimeMillis());
            Privilege.setAuthorization(req, auth);

            OnlineUserDb ou = new OnlineUserDb();
            ou = ou.getOnlineUserDb(auth.getName());
            ou.setStayTime(new java.util.Date());
            // 如果用户在线
            if (ou.isLoaded()) {
            	// 如果
                ou.save();
            } else {
                // 如果不在线，即超时被刷新掉了，则再加入在线列表
                // int isguest = 0;
                ou.setName(auth.getName());
                ou.setIp(StrUtil.getIp(req));
                ou.setSessionId(req.getSession().getId());
                // ou.setGuest(isguest == 1 ? true : false);
                ou.create();
                // logger.info("setStayTime: create " + username + " isguest=" + isguest);
            }
    }

}
